<template>
  <div class="box">
    <!-- 登录后 -->
    <Dropdown v-if="userName" @on-click="logoutHandle">
      <a href="javascript:void(0)">
        <Icon type="ios-person" size="20" />
        {{ userName }}
        <Icon type="ios-arrow-down"></Icon>
      </a>
      <template #list>
        <DropdownMenu>
          <DropdownItem>退出登录</DropdownItem>
        </DropdownMenu>
      </template>
    </Dropdown>
    <!-- 登录前 -->
    <Button v-else shape="circle" icon="ios-person" @click="modal = true"></Button>

    <!-- 登录注册弹框 -->
    <Modal v-model="modal" footer-hide>
      <h3>{{ $t('login.title') }}</h3>
      <Tabs :animated="false" @on-click="switchTab">
        <!-- 登录 -->
        <TabPane :label="$t('login.login')">
          <Form ref="loginForm" :model="formInline" :rules="ruleInline" class="form-box">
            <FormItem prop="email">
              <Input type="text" v-model="formInline.email" :placeholder="$t('login.email')">
                <template #prepend>
                  <Icon type="ios-mail-outline" />
                </template>
              </Input>
            </FormItem>
            <FormItem prop="password">
              <Input type="password" v-model="formInline.password" :placeholder="$t('login.password')">
                <template #prepend>
                  <Icon type="ios-lock-outline"></Icon>
                </template>
              </Input>
            </FormItem>
            <FormItem>
              <Button type="primary" long @click="loginHandle">
                {{ $t('login.login') }}
              </Button>
            </FormItem>
            <div style="width: 100%; text-align: center;">
              <span class="forget-password" @click="resetPasswordBtn">{{ $t('login.resetPassword') }}</span>
            </div>
          </Form>
        </TabPane>

        <!-- 注册 -->
        <TabPane :label="$t('login.register')">
          <Form ref="registerForm" :model="registerFormInline" :rules="registerRuleInline" class="form-box">
            <FormItem prop="email">
              <Input type="text" v-model="registerFormInline.email" :placeholder="$t('login.email')">
                <template #prepend>
                  <Icon type="ios-mail-outline" />
                </template>
              </Input>
            </FormItem>
            <FormItem prop="password">
              <Input type="password" :password="true" v-model="registerFormInline.password" :placeholder="$t('login.password')">
                <template #prepend>
                  <Icon type="ios-lock-outline"></Icon>
                </template>
              </Input>
            </FormItem>
            <FormItem prop="confirmPassword">
              <Input type="password" v-model="registerFormInline.confirmPassword" :placeholder="$t('login.confirmPassword')">
                <template #prepend>
                  <Icon type="ios-lock-outline"></Icon>
                </template>
              </Input>
            </FormItem>
            <FormItem prop="verificationCode">
              <Row :gutter="20">
                <Col span="18">
                  <Input type="text" v-model="registerFormInline.verificationCode" :placeholder="$t('login.verificationCode')">
                    <template #prepend>
                      <Icon type="md-apps">"></Icon>
                    </template>
                  </Input>
                </Col>
                <Col span="6">
                  <Button type="primary" :disabled="isCountingDown" @click="startCountdown">
                    <span v-if="isCountingDown">{{ secondsRemaining + '秒后重发' }}</span>
                    <span v-else>{{ $t('login.getVerificationCode') }}</span>
                  </Button>
                </Col>
              </Row>
            </FormItem>
            <FormItem>
              <Button type="primary" long @click="registerHandle">
                {{ $t('login.register') }}
              </Button>
            </FormItem>
          </Form>
        </TabPane>
      </Tabs>
    </Modal>

    <Modal v-model="modalResetPassword" footer-hide width="500px">
      <h3>{{ $t('login.resetPassword') }}</h3>
      <Form ref="resetPasswordRef" :model="resetPasswordForm" :rules="resetPasswordRule" class="form-box">
        <FormItem prop="email">
          <Input type="text" v-model="resetPasswordForm.email" :placeholder="$t('login.email')">
            <template #prepend>
              <Icon type="ios-mail-outline" />
            </template>
          </Input>
        </FormItem>
        <FormItem prop="password">
          <Input type="password" :password="true" v-model="resetPasswordForm.password" :placeholder="$t('login.password')">
            <template #prepend>
              <Icon type="ios-lock-outline"></Icon>
            </template>
          </Input>
        </FormItem>
        <FormItem prop="confirmPassword">
          <Input type="password" v-model="resetPasswordForm.confirmPassword" :placeholder="$t('login.confirmPassword')">
            <template #prepend>
              <Icon type="ios-lock-outline"></Icon>
            </template>
          </Input>
        </FormItem>
        <FormItem prop="verificationCode">
          <Row :gutter="20">
            <Col span="18">
              <Input type="text" v-model="resetPasswordForm.verificationCode" :placeholder="$t('login.verificationCode')">
                <template #prepend>
                  <Icon type="md-apps">"></Icon>
                </template>
              </Input>
            </Col>
            <Col span="6">
              <Button type="primary" :disabled="isCountingDown" @click="startCountdown">
                <span v-if="isCountingDown">{{ secondsRemaining + '秒后重发' }}</span>
                <span v-else>{{ $t('login.getVerificationCode') }}</span>
              </Button>
            </Col>
          </Row>
        </FormItem>
        <FormItem>
          <Button type="primary" long @click="resetBtn">
            {{ $t('login.reset') }}
          </Button>
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script setup name="Login">
import { useI18n } from 'vue-i18n';
import {
  getUserInfo,
  setToken,
  login,
  register,
  logout,
  getCode,
  resetPasswordApi,
  setUserName
} from "@/api/user";
import { Message, Modal } from 'view-ui-plus';
const modal = ref(false);
const modalResetPassword = ref(false);
const { t } = useI18n();
const userName = ref('');
// 获取用户详情
// getUserInfo()
//   .then((res) => {
//     userName.value = res.data.username;
//   })
//   .catch(() => {
//     logout();
//   });

const reloadPage = () => {
  setTimeout(() => {
    window.location.reload();
  }, 1000);
};
// 退出
const logoutHandle = () => {
  Modal.confirm({
    title: t('login.logoutTip'),
    onOk: () => {
      logout();
      Message.success(t('login.logoutSuccessTip'));
      reloadPage();
    },
  });
};
// 登录逻辑 ------------------
const formInline = reactive({
  email: '',
  password: '',
});
const ruleInline = reactive({
  email: [
    { required: true, message: t('login.emailValidate'), trigger: 'blur' },
    { type: 'email', message: t('login.emailValidate'), trigger: 'blur', },
  ],
  password: [
    { required: true, message: t('login.passwordValidate'), trigger: 'blur' },
    { type: 'string', min: 6, message: t('login.passwordValidate'), trigger: 'blur', },
  ],
});
const loginForm = ref(null);

const loginHandle = () => {
  loginForm.value.validate((valid) => {
    if (valid) {
      let data = {
        username:formInline.email,
        password:formInline.password
      }
      login(data).then((res) => {
        const code = res.data.code;
        if(code === 200){
          setToken(res.data.msg);
          setUserName(formInline.email)
          Message.success(t('login.welcome'));
          reloadPage();
        }else{
          Message.error(res.data.msg || '注册失败');
        }
      })
    }
  });
};

// 注册逻辑 分割线--------------------
const registerFormInline = reactive({
  email: '',
  confirmPassword: '',
  password: '',
  verificationCode: '',
  uuid: '',
});
const codeStatus = ref(false);
let intervalId;
const secondsRemaining = ref(60);
const isCountingDown = ref(false);

// 发送验证码-倒计时
const startCountdown = () => {
  const email = registerFormInline.email || resetPasswordForm.email
  if(!email){
    Message.error(t('login.emailValidate'));
    return;
  }
  getVerificationCode(email)
};

// 发送验证码
const getVerificationCode = (email) => {
  getCode(email).then((res)=>{
    const code = res.data.code;
    if(code === 200){
      Message.success('验证码已发送，请查看邮箱');
      registerFormInline.uuid = res.data.msg
      resetPasswordForm.uuid = res.data.msg
      if (!isCountingDown.value) {
        isCountingDown.value = true;
        intervalId = setInterval(() => {
          secondsRemaining.value--;
          if (secondsRemaining.value <= 0) {
            clearInterval(intervalId);
            isCountingDown.value = false;
            secondsRemaining.value = 60; // reset the countdown for next time
          }
        }, 1000);
      }
    }else{
      Message.error( res.data.msg || t('login.emailValidate'));
    }
  })
}

const registerRuleInline = reactive({
  password: [
    { required: true, message: t('login.passwordValidate'), trigger: 'blur' },
    {
      type: 'string',
      min: 6,
      message: t('login.passwordValidate'),
      trigger: 'blur',
    },
  ],
  email: [
    { required: true, message: t('login.emailValidate'), trigger: 'blur' },
    {
      type: 'email',
      message: t('login.emailValidate'),
      trigger: 'blur',
    },
  ],
  confirmPassword: [
    { required: true, message: t('login.confirmPasswordValidate'), trigger: 'blur' },
    {
      type: 'string',
      min: 6,
      message: t('login.confirmPasswordValidate'),
      trigger: 'blur',
    },
    {
      validator: (rule, value, callback) => {
        if (value !== registerFormInline.password) {
          callback(new Error(t('login.confirmPasswordValidate')));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
  verificationCode: [
    { required: true, message: t('login.verificationCodeValidate'), trigger: 'blur' },
  ],
});
const registerForm = ref(null);

const registerHandle = () => {
  registerForm.value.validate((valid) => {
    if (valid) {
      let data = {
        uuid: registerFormInline.uuid,
        email: registerFormInline.email,
        password:registerFormInline.password,
        secondCipher:registerFormInline.confirmPassword,
        code: registerFormInline.verificationCode,
      }
      console.log("注册",data);
      register(data).then((res) => {
        console.log("res",res);
        // setToken(res.data.msg);
        // Message.success(t('login.welcome'));
        // reloadPage();
        const code = res.data.code;
        if(code === 200){
          Message.success('注册成功');
          registerForm.value && registerForm.value.resetFields();
        }else{
          Message.error(res.data.msg || '注册失败');
        }
      })
    }
  });
};

// 忘记密码逻辑 分割线--------------------
const resetPasswordBtn = () => {
  clearInterval(intervalId);
  isCountingDown.value = false;
  secondsRemaining.value = 60;
  modalResetPassword.value = !modalResetPassword.value;
  resetPasswordRef.value && resetPasswordRef.value.resetFields();
}

const resetPasswordForm = reactive({
  email: '',
  confirmPassword: '',
  password: '',
  verificationCode: '',
  uuid: '',
});

const resetPasswordRule = reactive({
  password: [
    { required: true, message: t('login.passwordValidate'), trigger: 'blur' },
    {
      type: 'string',
      min: 6,
      message: t('login.passwordValidate'),
      trigger: 'blur',
    },
  ],
  email: [
    { required: true, message: t('login.emailValidate'), trigger: 'blur' },
    {
      type: 'email',
      message: t('login.emailValidate'),
      trigger: 'blur',
    },
  ],
  confirmPassword: [
    { required: true, message: t('login.confirmPasswordValidate'), trigger: 'blur' },
    {
      type: 'string',
      min: 6,
      message: t('login.confirmPasswordValidate'),
      trigger: 'blur',
    },
    {
      validator: (rule, value, callback) => {
        if (value !== resetPasswordForm.password) {
          callback(new Error(t('login.confirmPasswordValidate')));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
  verificationCode: [
    { required: true, message: t('login.verificationCodeValidate'), trigger: 'blur' },
  ],
});
const resetPasswordRef = ref(null);

const resetBtn = () => {
  resetPasswordRef.value.validate((valid) => {
    if (valid) {
      let data = {
        uuid: resetPasswordForm.uuid,
        email: resetPasswordForm.email,
        password:resetPasswordForm.password,
        secondCipher:resetPasswordForm.confirmPassword,
        code: resetPasswordForm.verificationCode,
      }
      console.log("重置密码",data);
      resetPasswordApi(data).then((res) => {
        console.log("res",res);
        const code = res.data.code;
        if(code === 200){
          modalResetPassword.value = !modalResetPassword.value;
          Message.success('重置成功');
          registerForm.value && registerForm.value.resetFields();
        }else{
          Message.error(res.data.msg || '重置失败');
        }
      })
    }
  });
}

const switchTab = () => {
  clearInterval(intervalId);
  isCountingDown.value = false;
  secondsRemaining.value = 60;
  registerForm.value && registerForm.value.resetFields();
  loginForm.value && loginForm.value.resetFields();
};

onUnmounted(() => {
  clearInterval(intervalId);
});
</script>
<style scoped lang="less">
.box {
  display: inline-block;
}
.form-box {
  padding-top: 10px;
}
h3 {
  padding-bottom: 10px;
}

.forget-password {
  font-style: italic;
  border-bottom: 2px solid transparent; /* 初始状态下无下划线 */
  padding-bottom: 2px; /* 确保文本与下划线之间有适当间距 */
  color: #333; /* 默认文本颜色 */
  transition: all 0.3s ease-in-out; /* 平滑过渡效果 */
}

/* 悬停时的效果 */
.forget-password:hover {
  color: #2d8cf0; /* 改变文本颜色 */
  border-bottom-color: #2d8cf0; /* 添加蓝色下划线 */
  cursor: pointer; /* 更改鼠标指针为手型 */
}
</style>
